<template>
  <div class="search-container">
    <button class="back-button" @click="goBack">
      <span class="back-icon">←</span>
      <span class="back-text">返回</span>
    </button>

    <div class="search-header">
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索商品"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #suffix>
            <el-icon class="search-icon" @click="handleSearch"><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <div class="search-results" v-if="!loading">
      <div v-if="products.length === 0" class="empty-state">
        <el-empty description="未找到相关商品" />
      </div>
      
      <div v-else class="product-grid">
        <div v-for="product in products" :key="product.id" class="product-card" @click="goToDetail(product.id)">
          <div class="product-image">
            <img :src="product.image" :alt="product.name">
          </div>
          <div class="product-info">
            <h3 class="product-name">{{ product.name }}</h3>
            <p class="product-description">{{ product.description }}</p>
            <div class="product-footer">
              <span class="product-price">¥{{ formatPrice(product.price) }}</span>
              <span class="product-stock">库存: {{ product.stock }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div v-else class="loading-state">
      <el-skeleton :rows="5" animated />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { searchByName } from '@/axios/product'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const searchKeyword = ref('')
const products = ref([])
const loading = ref(false)

// 返回上一页
const goBack = () => {
  router.back()
}

// 格式化价格
const formatPrice = (price) => {
  return Number(price).toFixed(2)
}

// 跳转到商品详情
const goToDetail = (productId) => {
  router.push({
    name: 'product-detail',
    params: { id: productId }
  })
}

// 搜索商品
const handleSearch = async () => {
  const keyword = searchKeyword.value.trim()
  if (!keyword) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  loading.value = true
  try {
    console.log('开始搜索，关键词:', keyword)
    const response = await searchByName(keyword)
    console.log('搜索请求完成，响应:', response)
    
    if (response && response.code === 1) {
      products.value = response.data
        .filter(item => item.status !== 0)
        .map(item => ({
          ...item,
          image: item.image || 'https://images.unsplash.com/photo-1607623814075-e51df1bdc82f?w=500&auto=format&fit=crop&q=60'
        }))
    } else {
      console.error('搜索响应异常:', response)
      ElMessage.error(response?.msg || '搜索失败')
      products.value = []
    }
  } catch (error) {
    console.error('搜索请求失败:', error)
    ElMessage.error('搜索失败，请稍后重试')
    products.value = []
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // 如果有查询参数，自动搜索
  const keyword = route.query.keyword
  if (keyword) {
    console.log('从URL获取搜索关键词:', keyword)
    searchKeyword.value = keyword
    handleSearch()
  }
})
</script>

<style scoped>
.search-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px;
  min-height: 100vh;
  background-color: #f8f9fa;
}

.back-button {
  position: absolute;
  top: 20px;
  left: 30px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background: white;
  border: none;
  border-radius: 30px;
  font-size: 16px;
  color: #2c3e50;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.back-button:hover {
  transform: translateX(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.back-icon {
  font-size: 20px;
  font-weight: 500;
}

.back-text {
  font-weight: 500;
}

.search-header {
  margin: 60px 0 30px;
}

.search-box {
  max-width: 600px;
  margin: 0 auto;
}

.search-icon {
  cursor: pointer;
  font-size: 20px;
  color: #409EFF;
}

.search-results {
  margin-top: 30px;
}

.empty-state {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.product-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.product-image {
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  padding: 15px;
}

.product-name {
  margin: 0;
  font-size: 16px;
  color: #2c3e50;
  font-weight: 500;
}

.product-description {
  margin: 10px 0;
  font-size: 14px;
  color: #666;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.product-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: 600;
}

.product-stock {
  color: #909399;
  font-size: 14px;
}

.loading-state {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}
</style> 